package edu.cmu.ece.ds.droidchat;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import edu.cmu.ece.ds.droidchat.NetworkService.LocalBinder;
import edu.cmu.ece.ds.droidchat.message.ClientRegisterResponseMessage;
import edu.cmu.ece.ds.droidchat.model.StringConstants;

public class RegisterActivity extends Activity {
    private final String TAG = "RegisterActivity";

    // Layout Views
    private Button mRegisterButton;
    private TextView mUsername;
    private TextView mPassword;

    private NetworkService mService; // the Service component
    private boolean mBound = false;

    private ProgressDialog register_dialog = null;
    private ServerMessageReceiver mReceiver; // the BroadcastReceiver component

    private boolean isRegistering = false;

    // The action listener for the EditText widget, to listen for the return key
    private TextView.OnEditorActionListener mWriteListener = new TextView.OnEditorActionListener() {
        public boolean onEditorAction(TextView view, int actionId,
                KeyEvent event) {
            // If the action is a key-up event on the return key, send the
            // message
            if (actionId == EditorInfo.IME_NULL
                    && event.getAction() == KeyEvent.ACTION_UP) {
                Log.i(TAG, "Enter Key is pressed");
            }
            return true;
        }
    };

    public class ServerMessageReceiver extends BroadcastReceiver {
        public static final String TAG = "ServerMessageReceiver";

        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "onReceive: " + intent);
            String userid = intent
                    .getStringExtra(StringConstants.EXTRA_USER_NAME);
            int response = intent
                    .getIntExtra(StringConstants.EXTRA_RESPONSE, 0);
            Log.d(TAG, "userid: " + userid);
            Log.d(TAG, "response: " + response);

            if (isRegistering) {
                register_dialog.dismiss();
                if (response == ClientRegisterResponseMessage.REGISTER_SUCCESSFUL) {
                    Toast.makeText(
                            getApplicationContext(),
                            "Registration request with userid='" + userid
                                    + "' was successful!", Toast.LENGTH_LONG)
                            .show();
                } else {
                    Toast.makeText(
                            getApplicationContext(),
                            "Registration request with userid='"
                                    + userid
                                    + "' was NOT successful because it has already been registered!",
                            Toast.LENGTH_LONG).show();
                }
            }// else i really don't care
        }
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.registration);
        mRegisterButton = (Button) findViewById(R.id.register);
        mUsername = (EditText) findViewById(R.id.user_id);
        mPassword = (EditText) findViewById(R.id.password);

        // Initialize the username and password field with a listener for the
        // "return key"
        mUsername.setOnEditorActionListener(mWriteListener);
        mPassword.setOnEditorActionListener(mWriteListener);
        mReceiver = new ServerMessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(StringConstants.ACTION_CLIENT_REGISTER_RESPONSE);
        Log.d(TAG, "ServerMessageReceiver registered! ");
        this.registerReceiver(mReceiver, filter);
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "---onStart---");
        Intent intent = new Intent(this, NetworkService.class);
        Log.d(TAG, "calling bindService()");
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

        // Initialize the Register button with a listener that for click events
        mRegisterButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // Opens Socket to contact the servers
                Log.d(TAG, "Register Button is pressed");

                if (mUsername.getText().toString().equals("")) {
                    Log.d(TAG, "username is not entered");
                    Toast.makeText(getApplicationContext(),
                            R.string.register_none_entered, Toast.LENGTH_SHORT)
                            .show();
                } else if (mPassword.getText().toString().equals("")) {
                    Log.d(TAG, "password is not entered");
                    Toast.makeText(getApplicationContext(),
                            R.string.register_none_entered, Toast.LENGTH_SHORT)
                            .show();
                } else {
                    Log.d(TAG, mUsername.getText().toString());
                    Log.d(TAG, mPassword.getText().toString());

                    if (mService.isConnectedToServer()) {
                        Log.d(TAG, "TCPService has a connection with server");
                    } else {
                        Log.d(TAG,
                                "TCPService does NOT have a connection with server");
                    }

                    if (mBound == true) {
                        if (mService.isConnectedToServer()) {
                            Log.d(TAG, "mBound is true");
                            // asks the service to send ClientRegisterMessage to
                            // the DroidChat server
                            mService.register(mUsername.getText().toString(),
                                    mPassword.getText().toString());
                            isRegistering = true;
                            showDialog(REGISTERING_ID);
                        } else {
                            Toast.makeText(getApplicationContext(),
                                    R.string.login_error_server_down,
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }
        });
    }

    // most likely the user pressed back to go back to the LogInActivity
    public void onStop() {
        super.onStop();
        Log.d(TAG, "---onStop---");
        Log.d(TAG, "---calling unbindService---");
        unbindService(mConnection);
        /*
         * Log.d(TAG, "---finishing RegisterActivity---"); finish();
         */
    }

    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "---onDestroy---");
        unregisterReceiver(mReceiver);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Log.d(TAG, "---onConfigurationChanged---");
        setContentView(R.layout.registration);
    }

    /** Defines callbacks for service binding, passed to bindService() */
    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            // We've bound to TCPService, cast the IBinder and get TCPService
            // instance
            LocalBinder binder = (LocalBinder) service;
            mService = binder.getService();
            mBound = true;
            Log.d(TAG, "We've bound to TCPService");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBound = false;
        }
    };

    static final int REGISTERING_ID = 0;

    protected Dialog onCreateDialog(int id) {
        Dialog dialog;
        switch (id) {
        case REGISTERING_ID:
            /*
             * AlertDialog.Builder builder = new AlertDialog.Builder(this);
             * builder.setMessage("Registering... Please Wait")
             * .setCancelable(false) // cannot be cancelled by the BACK key, use
             * 'ABORT' .setNegativeButton("Abort", new
             * DialogInterface.OnClickListener() {
             *
             * public void onClick(DialogInterface dialog, int which) {
             * dialog.cancel(); } }); dialog = builder.create();
             */
            break;
        default:
            dialog = null;
        }
        register_dialog = register_dialog.show(RegisterActivity.this, "",
                "Registering. Please Wait...");
        return register_dialog;
    }
}
